package com.jie.utility;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class CreateES {
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.246.128:9200")
        ));
    }

    /**
     * 创建索引库
     * @param index 索引库名称
     * @param json 索引库
     * @throws IOException
     */
    public void  createIndex(String index,String json) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(index);
        request.source(json, XContentType.JSON);
        client().indices().create(request, RequestOptions.DEFAULT);
    }

    /**
     * 删除索引库
     *  @param index 索引库名称
     * @throws IOException
     */
    public void delIndex(String index) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        client().indices().delete(request,RequestOptions.DEFAULT);
    }

    /**
     * 判断索引库是否存在
     * @param index 索引库名称
     * @return ture,fales
     * @throws IOException
     */
    public Boolean existtsIndex(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        boolean exists = client().indices().exists(request, RequestOptions.DEFAULT);
        return exists;
    }

}
